"""
交易管理路由
"""
from fastapi import APIRouter, Depends, HTTPException, status, Query
from sqlalchemy.orm import Session
from typing import List, Optional
from datetime import datetime

from database import get_db
from auth import get_current_active_user
from models import Trade, Product, User, TradeStatusHistory, Wallet
from schemas import TradeResponse, TradeCreate, TradeUpdate, BaseResponse, PaginatedResponse

router = APIRouter()

@router.post("/", response_model=TradeResponse)
async def create_trade(
    trade_data: TradeCreate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """创建交易"""
    # 检查商品是否存在且可交易
    product = db.query(Product).filter(
        Product.id == trade_data.product_id,
        Product.status == 'available'
    ).first()
    
    if not product:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="商品不存在或不可交易"
        )
    
    # 检查是否购买自己的商品
    if product.seller_id == current_user.id:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="不能购买自己的商品"
        )
    
    # 检查商品是否已有进行中的交易
    active_trades = db.query(Trade).filter(
        Trade.product_id == trade_data.product_id,
        Trade.status.in_(['pending_payment', 'paid', 'shipped'])
    ).count()
    
    if active_trades > 0:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="商品已有进行中的交易"
        )
    
    # 创建交易
    trade = Trade(
        product_id=trade_data.product_id,
        buyer_id=current_user.id,
        seller_id=product.seller_id,
        price=product.price,
        status='pending_payment'
    )
    
    db.add(trade)
    db.commit()
    db.refresh(trade)
    
    # 记录交易状态变更
    status_history = TradeStatusHistory(
        trade_id=trade.id,
        status='pending_payment',
        note="交易创建"
    )
    db.add(status_history)
    db.commit()
    
    return trade

@router.get("/", response_model=PaginatedResponse)
async def get_trades(
    page: int = Query(1, ge=1, description="页码"),
    size: int = Query(20, ge=1, le=100, description="每页数量"),
    role: Optional[str] = Query(None, description="角色：buyer（买家）/seller（卖家）"),
    status: Optional[str] = Query(None, description="交易状态"),
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """获取交易列表（分页）"""
    query = db.query(Trade)

@router.get("/my", response_model=PaginatedResponse)
async def get_my_trades(
    page: int = Query(1, ge=1, description="页码"),
    size: int = Query(20, ge=1, le=100, description="每页数量"),
    status: Optional[str] = Query(None, description="交易状态"),
    role: Optional[str] = Query(None, description="角色：buyer（买家）/seller（卖家）"),
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """获取我的交易列表（分页）"""
    query = db.query(Trade)
    
    # 根据角色筛选
    if role == 'buyer':
        query = query.filter(Trade.buyer_id == current_user.id)
    elif role == 'seller':
        query = query.filter(Trade.seller_id == current_user.id)
    else:
        # 默认显示用户相关的所有交易
        query = query.filter(
            (Trade.buyer_id == current_user.id) | 
            (Trade.seller_id == current_user.id)
        )
    
    # 状态筛选
    if status:
        query = query.filter(Trade.status == status)
    
    # 按创建时间倒序排列
    query = query.order_by(Trade.created_at.desc())
    
    # 分页
    total = query.count()
    trades = query.offset((page - 1) * size).limit(size).all()
    
    return PaginatedResponse(
        items=trades,
        total=total,
        page=page,
        size=size,
        pages=(total + size - 1) // size
    )

@router.get("/{trade_id}", response_model=TradeResponse)
async def get_trade(
    trade_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """获取交易详情"""
    trade = db.query(Trade).filter(Trade.id == trade_id).first()
    if not trade:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="交易不存在"
        )
    
    # 检查权限
    if trade.buyer_id != current_user.id and trade.seller_id != current_user.id:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="无权查看此交易"
        )
    
    return trade

@router.put("/{trade_id}/pay", response_model=BaseResponse)
async def pay_trade(
    trade_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """支付交易"""
    trade = db.query(Trade).filter(Trade.id == trade_id).first()
    if not trade:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="交易不存在"
        )
    
    # 检查权限
    if trade.buyer_id != current_user.id:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="无权操作此交易"
        )
    
    # 检查交易状态
    if trade.status != 'pending_payment':
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="交易状态不允许支付"
        )
    
    # 检查买家钱包余额
    buyer_wallet = db.query(Wallet).filter(Wallet.user_id == current_user.id).first()
    if not buyer_wallet or buyer_wallet.balance < trade.price:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="钱包余额不足"
        )
    
    # 扣款并更新交易状态
    buyer_wallet.balance -= trade.price
    trade.status = 'paid'
    
    # 记录交易状态变更
    status_history = TradeStatusHistory(
        trade_id=trade.id,
        status='paid',
        note="买家已支付"
    )
    db.add(status_history)
    db.commit()
    
    return BaseResponse(message="支付成功")

@router.put("/{trade_id}/ship", response_model=BaseResponse)
async def ship_trade(
    trade_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """发货"""
    trade = db.query(Trade).filter(Trade.id == trade_id).first()
    if not trade:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="交易不存在"
        )
    
    # 检查权限
    if trade.seller_id != current_user.id:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="无权操作此交易"
        )
    
    # 检查交易状态
    if trade.status != 'paid':
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="交易状态不允许发货"
        )
    
    # 更新交易状态
    trade.status = 'shipped'
    
    # 记录交易状态变更
    status_history = TradeStatusHistory(
        trade_id=trade.id,
        status='shipped',
        note="卖家已发货"
    )
    db.add(status_history)
    db.commit()
    
    return BaseResponse(message="发货成功")

@router.put("/{trade_id}/confirm", response_model=BaseResponse)
async def confirm_trade(
    trade_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """确认收货"""
    trade = db.query(Trade).filter(Trade.id == trade_id).first()
    if not trade:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="交易不存在"
        )
    
    # 检查权限
    if trade.buyer_id != current_user.id:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="无权操作此交易"
        )
    
    # 检查交易状态
    if trade.status != 'shipped':
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="交易状态不允许确认收货"
        )
    
    # 更新交易状态
    trade.status = 'completed'
    
    # 给卖家转账
    seller_wallet = db.query(Wallet).filter(Wallet.user_id == trade.seller_id).first()
    if seller_wallet:
        seller_wallet.balance += trade.price
    
    # 记录交易状态变更
    status_history = TradeStatusHistory(
        trade_id=trade.id,
        status='completed',
        note="买家已确认收货"
    )
    db.add(status_history)
    db.commit()
    
    return BaseResponse(message="确认收货成功")

@router.put("/{trade_id}/status", response_model=BaseResponse)
async def update_trade_status(
    trade_id: int,
    new_status: str,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """更新交易状态（通用接口）"""
    trade = db.query(Trade).filter(Trade.id == trade_id).first()
    if not trade:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="交易不存在"
        )
    
    # 根据新状态检查权限和状态转换合法性
    if new_status == 'paid':
        # 支付操作，只有买家可以执行
        if trade.buyer_id != current_user.id:
            raise HTTPException(
                status_code=status.HTTP_403_FORBIDDEN,
                detail="无权执行此操作"
            )
        if trade.status != 'pending_payment':
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="只有待付款状态的交易可以支付"
            )
        
        # 执行支付逻辑
        buyer_wallet = db.query(Wallet).filter(Wallet.user_id == current_user.id).first()
        if not buyer_wallet or buyer_wallet.balance < trade.price:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="钱包余额不足"
            )
        buyer_wallet.balance -= trade.price
        note = "买家已支付"
    
    elif new_status == 'shipped':
        # 发货操作，只有卖家可以执行
        if trade.seller_id != current_user.id:
            raise HTTPException(
                status_code=status.HTTP_403_FORBIDDEN,
                detail="无权执行此操作"
            )
        if trade.status != 'paid':
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="只有已支付状态的交易可以发货"
            )
        note = "卖家已发货"
    
    elif new_status == 'completed':
        # 确认收货操作，只有买家可以执行
        if trade.buyer_id != current_user.id:
            raise HTTPException(
                status_code=status.HTTP_403_FORBIDDEN,
                detail="无权执行此操作"
            )
        if trade.status != 'shipped':
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="只有已发货状态的交易可以确认收货"
            )
        
        # 执行确认收货逻辑（转账给卖家）
        seller_wallet = db.query(Wallet).filter(Wallet.user_id == trade.seller_id).first()
        if seller_wallet:
            seller_wallet.balance += trade.price
        note = "买家已确认收货"
    
    elif new_status == 'cancelled':
        # 取消操作，买卖双方都可以执行，但需满足状态条件
        if trade.buyer_id != current_user.id and trade.seller_id != current_user.id:
            raise HTTPException(
                status_code=status.HTTP_403_FORBIDDEN,
                detail="无权执行此操作"
            )
        if trade.status not in ['pending_payment', 'paid']:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="只有待付款或已支付状态的交易可以取消"
            )
        
        # 执行取消逻辑（退款）
        if trade.status == 'paid':
            buyer_wallet = db.query(Wallet).filter(Wallet.user_id == trade.buyer_id).first()
            if buyer_wallet:
                buyer_wallet.balance += trade.price
        note = "交易已取消"
    
    else:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="不支持的交易状态"
        )
    
    # 更新交易状态
    trade.status = new_status
    
    # 记录交易状态变更
    status_history = TradeStatusHistory(
        trade_id=trade.id,
        status=new_status,
        note=note
    )
    db.add(status_history)
    db.commit()
    
    return BaseResponse(message=f"交易状态已更新为{new_status}")

@router.put("/{trade_id}/cancel", response_model=BaseResponse)
async def cancel_trade(
    trade_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """取消交易"""
    trade = db.query(Trade).filter(Trade.id == trade_id).first()
    if not trade:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="交易不存在"
        )
    
    # 检查权限
    if trade.buyer_id != current_user.id and trade.seller_id != current_user.id:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="无权操作此交易"
        )
    
    # 检查交易状态
    if trade.status not in ['pending_payment', 'paid']:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="交易状态不允许取消"
        )
    
    # 如果是已支付状态，需要退款
    if trade.status == 'paid':
        # 检查权限（只有买家可以取消已支付的交易）
        if trade.buyer_id != current_user.id:
            raise HTTPException(
                status_code=status.HTTP_403_FORBIDDEN,
                detail="只有买家可以取消已支付的交易"
            )
        
        # 退款
        buyer_wallet = db.query(Wallet).filter(Wallet.user_id == trade.buyer_id).first()
        if buyer_wallet:
            buyer_wallet.balance += trade.price
    
    # 更新交易状态
    trade.status = 'cancelled'
    
    # 记录交易状态变更
    status_history = TradeStatusHistory(
        trade_id=trade.id,
        status='cancelled',
        note="交易已取消"
    )
    db.add(status_history)
    db.commit()
    
    return BaseResponse(message="交易取消成功")